package com.jifeng.sterilizer.service.impl;

import com.jifeng.sterilizer.entity.DeviceEntity;
import com.jifeng.sterilizer.service.DeviceService;
import com.jifeng.sterilizer.utils.R;
import com.jifeng.sterilizer.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jifeng.sterilizer.utils.PageUtils;
import com.jifeng.sterilizer.utils.Query;

import com.jifeng.sterilizer.dao.UserDeviceDao;
import com.jifeng.sterilizer.entity.UserDeviceEntity;
import com.jifeng.sterilizer.service.UserDeviceService;


@Service("userDeviceService")
@Slf4j
public class UserDeviceServiceImpl extends ServiceImpl<UserDeviceDao, UserDeviceEntity> implements UserDeviceService {

    @Autowired
    DeviceService deviceService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserDeviceEntity> page = this.page(
                new Query<UserDeviceEntity>().getPage(params),
                new QueryWrapper<UserDeviceEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R addUserDevice(UserDeviceEntity userDevice) {
        boolean save = this.save(userDevice);
        Map<String, Object> map = new HashMap<>();
        if (save) {
            DeviceEntity deviceEntity = deviceService.getOne(new QueryWrapper<DeviceEntity>().eq("number", userDevice.getDeviceNumber()));
            map.put("number", userDevice.getDeviceNumber());
            map.put("name", deviceEntity.getName());
            return R.ok().put("data", map);
        }
        return R.error();
    }

    @Override
    public R removeUserDevice(UserDeviceEntity userDevice) {
        try {
            boolean isNumber = RegexUtils.isNumber(String.valueOf(userDevice.getDeviceNumber()), 1);
            if (!isNumber) {
                log.warn("方法：{}，错误信息：{}", "解除用户和消毒机的绑定", "消毒机编号格式错误");
                return R.error(400, "消毒机编号格式错误");
            }
            boolean remove = this.remove(new QueryWrapper<UserDeviceEntity>().eq("user_id", userDevice.getUserId()).eq("device_number", userDevice.getDeviceNumber()));
            if (remove) {
                return R.ok();
            }
            log.warn("方法：{}，错误信息：{}", "解除用户和消毒机的绑定", "检查提交参数值是否有效");
            return R.error(400, "检查提交参数值是否有效");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "解除用户和消毒机的绑定", e.getMessage());
            return R.error(400, "系统繁忙");
        }
    }

}